package com.soulmate.auth.handle;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author huaiping
 */
@Component
@AllArgsConstructor
public class LoginFailureHandler implements AuthenticationFailureHandler {
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        String resp = "登录失败";
        // 这些对于操作的处理类可以根据不同异常进行不同处理
        if (exception instanceof UsernameNotFoundException){
            resp = objectMapper.writeValueAsString(
                    ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("用户名不存在"));
        }
        if (exception instanceof LockedException){
            resp = objectMapper.writeValueAsString(
                    ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("用户被冻结"));
        }
        if (exception instanceof BadCredentialsException){
            resp = objectMapper.writeValueAsString(
                    ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("用户名密码不正确"));
        }
        response.getWriter().write(resp);
    }
}
